package com.dony.common.utils.price;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.dony.common.core.redis.RedisCache;
import com.dony.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.util.concurrent.TimeUnit;

/**
 * 汇率工具
 *
 * @author dony
 */
@Slf4j
@Component
public class ExchangeRateUtils {
    @Value("${exchangerate-api.apikey}")
    private String API_KEY;
    @Value("${exchangerate-api.base_url}")
    private String BASE_URL;
    @Autowired
    RedisCache redisCache;

    /**
     * 计算人民币价格
     *
     * @param sourceCurrency
     * @param amount
     * @return
     */
    public String getRMBPrice(String sourceCurrency, float amount) {
        // 使用DecimalFormat来格式化输出，保留两位小数
        DecimalFormat df = new DecimalFormat("#.00");
        return df.format(getPrice(sourceCurrency, amount, "CNY"));
    }

    public Float getRMBPriceFloat(String sourceCurrency, float amount) {
        return getPrice(sourceCurrency, amount, "CNY");
    }


    /**
     * 计算转换之后会的汇率
     *
     * @param sourceCurrency
     * @param amount
     * @param targetCurrency
     * @return
     */
    public Float getPrice(String sourceCurrency, float amount, String targetCurrency) {
        return amount * getRate(sourceCurrency, targetCurrency);
    }


    /**
     * 获取汇率
     *
     * @param sourceCurrency
     * @param targetCurrency
     * @return
     */
    public Float getRate(String sourceCurrency, String targetCurrency) {
        Float redisRate = redisCache.getCacheObject("exchange-rate:" + sourceCurrency + "-" + targetCurrency);
        if (redisRate == null) {
            synchronized (this) {
                //获取在线汇率
                String url_str = BASE_URL + API_KEY + "/latest/" + sourceCurrency;
                String r = HttpUtil.get(url_str);
                JSONObject reslut = JSONObject.parseObject(r);
                //如果成功
                if (StringUtils.equals(reslut.getString("result"), "success")) {
                    redisRate = reslut.getJSONObject("conversion_rates").getFloat(targetCurrency);
                    redisCache.setCacheObject("exchange-rate:" + sourceCurrency + "-" + targetCurrency, redisRate, 1, TimeUnit.DAYS);
                    log.info("汇率保存成功！ exchange-rate:" + sourceCurrency + "-" + targetCurrency + ":" + redisRate);
                } else {
                    log.error("在线汇率获取失败");
                }
            }
        }
        return redisRate;
    }

    public String getRegionByCurrency(String currency) {
        switch (currency.toUpperCase()) {
            case "BRL":
                return "BR";
            case "CLP":
                return "CL";
            case "COP":
                return "CO";
            case "MXN":
                return "MX";
            case "MYR":
                return "MY";
            case "PHP":
                return "PH";
            case "SGD":
                return "SG";
            case "THB":
                return "TH";
            case "TWD":
                return "TW";
            case "VND":
                return "VN";
            default:
                return "";
        }

    }


}
